#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : extract_audio_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/22 09:53
"""
import shutil
import os
import traceback
from concurrent.futures import ThreadPoolExecutor, as_completed
from multiprocessing import Process

from worker.base_worker import BaseThread
from log import log
from core.audio.extract_audio import extract_audio_from_video, merge_mp3_files


def do_work(input_files, output_folder, status, queue):
    with ThreadPoolExecutor(max_workers=4) as executor:
        futures = []
        for input_file in input_files:
            queue.put(1)
            future = executor.submit(extract_audio_from_video, input_file, output_folder, ".mp3")
            futures.append(future)
        result = []
        for future in as_completed(futures):
            try:
                queue.put(1)
                result.append(future.result())
            except Exception as e:
                log.error(f"提取音频失败：{e}")
                traceback.print_exc()
    if status != 0:
        out_file = os.path.normpath(os.path.join(output_folder, "merged.mp3"))
        merge_mp3_files(result, out_file)
        for f in result:
            shutil.rmtree(f)
    queue.put("done")


class ExtractAudioWorker(BaseThread):
    """提取音频线程"""

    def __init__(self, params, parent=None):
        super(ExtractAudioWorker, self).__init__(params, parent)
        self.input_files = params["input_files"]
        self.output_folder = params["output_folder"]
        self.status = params["status"]


    def run(self):
        try:
            self.process = Process(target=do_work, args=(self.input_files, self.output_folder, self.status, self.queue))
            self.process.start()
            while True:
                msg = self.queue.get()
                if msg == "done":
                    break
                self.on_change_progress(msg)

        except Exception as e:
            self.failed.emit(e)
            traceback.print_exc()

